/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package services;

import dao.BuyJpaController;
import dao.CartJpaController;
import dao.ProductJpaController;
import dao.UserJpaController;
import dao.exceptions.NonexistentEntityException;
import dao.exceptions.PreexistingEntityException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Persistence;
import pojo.Buy;

import pojo.Cart;
import pojo.CartPK;
import pojo.Product;
import pojo.User;

/**
 *
 * @author khalifaabdelaziz
 */
public class ServiceCart {

    public List<Cart> findCartByUserId(Integer id) {

        UserJpaController userController = new UserJpaController(Persistence.createEntityManagerFactory("ServletProjectPU"));
        List<Cart> carts = userController.findUserCart(id);
        return carts;
    }

    public String countProductsInCart(Integer id) {

        UserJpaController userController = new UserJpaController(Persistence.createEntityManagerFactory("ServletProjectPU"));
        List<Cart> carts = userController.findUserCart(id);
        return "" + carts.size();
    }

    public String totalCartPrice(Integer id) {
        double total = 0.0;
        UserJpaController userController = new UserJpaController(Persistence.createEntityManagerFactory("ServletProjectPU"));
        List<Cart> carts = userController.findUserCart(id);
        for (Cart cart : carts) {

            total += (cart.getAmount() * cart.getProduct().getPrice());
        }
        return "" + total;
    }

    public String addtocart(Cart cart) {
        CartJpaController cartController = new CartJpaController(Persistence.createEntityManagerFactory("ServletProjectPU"));
        UserJpaController userController = new UserJpaController(Persistence.createEntityManagerFactory("ServletProjectPU"));
        ProductJpaController productController = new ProductJpaController(Persistence.createEntityManagerFactory("ServletProjectPU"));
        Product product = productController.findProduct(cart.getCartPK().getProductId());
        if (product.getAmount() >= cart.getAmount()) {
            cart.setUser(userController.findUser(cart.getCartPK().getUserId()));
            cart.setProduct(product);
            //System.out.println(""+cart.getUser().getId());
            CartPK cartPK = new CartPK(cart.getUser().getId(), cart.getProduct().getId());

            Cart cartexist = cartController.findCart(cartPK);
            //System.out.println(cartexist.getAmount());
            if (cartexist != null) {
                cartexist.setAmount(cartexist.getAmount() + cart.getAmount());
                if (product.getAmount() >= cartexist.getAmount()) {
                    try {
                        cartController.edit(cartexist);
                        return "added";
                    } catch (Exception ex) {
                        return "error" + ex.getMessage();
                    }
                } else {
                    return "out of stock";
                }
            } else {
                try {
                    cartController.create(cart);
                    return "added";
                } catch (Exception ex) {

                    return "error" + ex.getMessage();
                }
            }

        } else {
            return "out of stock";
        }

    }

    public String removeProductCart(Integer uId, Integer pId) {

        CartJpaController cartController = new CartJpaController(Persistence.createEntityManagerFactory("ServletProjectPU"));
        CartPK cpk = new CartPK();
        cpk.setUserId(uId);
        cpk.setProductId(pId);
        try {
            cartController.destroy(cpk);
            return "removed";
        } catch (NonexistentEntityException ex) {
            return ex.getMessage();
        }
    }

    public List<Cart> buyProductsInCart(Integer id) { // null if error, size <= 0 empty list done buy ,size>0 out of stock products
        UserJpaController userController = new UserJpaController(Persistence.createEntityManagerFactory("ServletProjectPU"));
        List<Cart> carts = userController.findUserCart(id);
        User user = userController.findUser(id);
        BuyJpaController buyController = new BuyJpaController(Persistence.createEntityManagerFactory("ServletProjectPU"));
        ProductJpaController productController = new ProductJpaController(Persistence.createEntityManagerFactory("ServletProjectPU"));

        if (carts.size() <= 0) {
            return null;
        } else {
            List<Cart> cartsOutOfStock = new ArrayList<Cart>();
            for (Cart cart : carts) {

                Product product = productController.findProduct(cart.getCartPK().getProductId());
                if (product.getAmount() < cart.getAmount()) {

                    cartsOutOfStock.add(cart);

                }

            }

            if (cartsOutOfStock.size() <= 0) {
                for (Cart cart : carts) {

                    Product product = productController.findProduct(cart.getCartPK().getProductId());
                    if (product.getAmount() >= cart.getAmount()) {

                        Buy buy = new Buy();
                        buy.setAmount(cart.getAmount());
                        buy.setUserId(cart.getUser());
                        buy.setProductId(cart.getProduct());
                        buy.setTime(new Date(System.currentTimeMillis()));

                        buyController.create(buy);
                        product.setAmount(product.getAmount() - cart.getAmount());
                        try {
                            productController.edit(product);
                        } catch (NonexistentEntityException ex) {
                            Logger.getLogger(ServiceCart.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (Exception ex) {
                            Logger.getLogger(ServiceCart.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        double total = (product.getPrice()*cart.getAmount());
                        User user1 = userController.findUser(id);
                        double usercredit =Double.parseDouble(user1.getCredit());
                        usercredit -= total;
                        user1.setCredit(""+usercredit);
                        try {
                            userController.edit(user1);
                        } catch (NonexistentEntityException ex) {
                            Logger.getLogger(ServiceCart.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (Exception ex) {
                            Logger.getLogger(ServiceCart.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        removeProductCart(id, cart.getCartPK().getProductId());

                    }
                }
                

            } else {
                return cartsOutOfStock;
            }

            return cartsOutOfStock;
        }

    }
//    public static void main(String[] args) {
////
////         System.out.println(new ServiceCart().totalCartPrice(4));
////         System.out.println(new ServiceCart().countProductsInCart(4));
// //           new ServiceCart().buyProductsInCart(4);
//    }

}
